import React, { useMemo, useRef, useState } from "react";
import { useDroppable, useDndMonitor, Active } from "@dnd-kit/core";
import { guid, FunFormElement } from "../../core";
import { WidgetConstructor } from "../../widgets";
import WrapItem, { WarpAction } from "./toolWrap";
import DropItem from "./dropItem";
import { useHover } from "ahooks";
import classNames from "classnames";
import styles from "../index.module.less";

const DefaultDropBlock = (props: {
  labelWidths: number[];
  onTrigger(type: WarpAction): void;
  couldDelete: boolean;
  uuid: string;
  updateColunm(column: FunFormCardColumn[]): void;
  onWidgetMoveIn(widget: FunFormWidget, colId: string, at: number): void;
}) => {
  const { setNodeRef } = useDroppable({
    id: props.uuid,
  });

  const ref = useRef(null);

  const isHovering = useHover(ref);

  const [isOver, setIsOver] = useState(false);

  const [actived, setActived] = useState<Active>();

  useDndMonitor({
    onDragEnd() {
      setIsOver(false);
    },
    onDragMove({ over }) {
      if (over?.id) {
        setIsOver(over.id.includes(props.uuid));
      } else {
        setIsOver(false);
      }
    },
    onDragStart({ active }) {
      setActived(active);
    },
  });

  //// 根据选择组件类型 决定渲染列数
  const dropList = useMemo(() => {
    let list = props.labelWidths;
    if (!actived) return list;
    else {
      const { name: activeName, ...value } = actived.data.current as {
        name: FunFormElement;
      };
      if (activeName === FunFormElement.Cagetroy) {
        const val = (value as { value: WidgetCategory }).value;
        if (val.allwaysFull) return [props.labelWidths[0]];
      } else if (activeName === FunFormElement.Widget) {
        const val = (value as { value: FunFormWidget }).value;
        if (val.category.allwaysFull) return [props.labelWidths[0]];
      }
    }
    return list;
  }, [actived, props.labelWidths]);

  return (
    <div className={styles.rowBlock} ref={setNodeRef}>
      {!isOver && (
        <WrapItem
          onTrigger={props.onTrigger}
          actions={
            props.couldDelete
              ? [
                  WarpAction.deleteRow,
                  WarpAction.insertLeft,
                  WarpAction.insertRight,
                ]
              : [WarpAction.insertLeft, WarpAction.insertRight]
          }
        >
          <div
            ref={ref}
            className={classNames(
              styles.blockDrop,
              isHovering && styles.isHovering
            )}
          >
            <div className={styles.tip}>点击或者拖入左侧组件</div>
          </div>
        </WrapItem>
      )}
      {isOver &&
        dropList.map((_, at, { length: len }) => {
          return (
            <div key={props.uuid + "_" + at} className={styles.item}>
              <DropItem
                id={props.uuid + "_" + at}
                onDrop={() => {
                  if (!actived) return;
                  let { name, value, colId } = actived.data.current as {
                    name: FunFormElement;
                    value: WidgetCategory | FunFormWidget;
                    colId: string;
                  };
                  if (name === FunFormElement.Cagetroy) {
                    /// 根据分类 创建列
                    const { defaultFull, allwaysFull } =
                      value as WidgetCategory;
                    let columns: FunFormCardColumn[] = [];
                    if (defaultFull || allwaysFull) {
                      columns = [
                        {
                          uuid: guid(),
                          category: value as WidgetCategory,
                          widget: WidgetConstructor(value as WidgetCategory),
                          colSpan: props.labelWidths.length, // 占用格子数
                        },
                      ];
                    } else
                      columns = new Array(len).fill("").map((_, i) => {
                        return {
                          uuid: guid(),
                          colSpan: 1,
                          widget:
                            i === at
                              ? WidgetConstructor(value as WidgetCategory)
                              : undefined,
                          category:
                            i === at ? (value as WidgetCategory) : undefined, // 放置位置添加一个weiget
                        };
                      });
                    props.updateColunm(columns);
                  } else if (name === FunFormElement.Widget) {
                    props.onWidgetMoveIn(value as FunFormWidget, colId, at);
                  }
                }}
              ></DropItem>
            </div>
          );
        })}
    </div>
  );
};

export default DefaultDropBlock;
